package com.ffzx.commerce.framework.interceptor;

import java.io.PrintWriter;
import java.util.Iterator;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

/**
 * 上传文件拦截器，定义只能上传某种类型的文件
 * 
 * @author Alvin
 * @date 2016年4月22日
 * @version 1.0
 */
public class FileUploadInterceptor extends HandlerInterceptorAdapter {

	final static String SUFFIXLIST="xls,xlsx,jpg,png,ico,bmp,jpeg";
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(
				request.getSession().getServletContext());
		if (multipartResolver.isMultipart(request)) {
			MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
			Map<String, MultipartFile> files= multiRequest.getFileMap();
			Iterator<String> iterator = files.keySet().iterator();
			while (iterator.hasNext()) {
				String formKey = (String) iterator.next();
				MultipartFile multipartFile = multiRequest.getFile(formKey);
				String name = "";
				if(multipartFile!=null && StringUtils.isNotBlank(name = multipartFile.getOriginalFilename())){
					if(validaeFile(name)){
						return true;
					}else{
						//不是ajax请求时后退
						if(request.getHeader("x-requested-with") == null){
							response.setCharacterEncoding("utf-8");
							response.setContentType("text/html;charset=utf-8");
							PrintWriter pt = response.getWriter();
							pt.write("<html><head><script>alert('上传的文件格式必须是["+SUFFIXLIST+"]');history.go(-1);</script></head></html>");
							pt.flush();
							pt.close();
						}
						return false;
					}
				}
			}
		}
		return super.preHandle(request, response, handler);
	}
	
	private  boolean validaeFile(String fileName){
		boolean flag=false;
		String suffix=fileName.substring(fileName.lastIndexOf(".")+1);
		if(SUFFIXLIST.contains(suffix.trim().toLowerCase())){
			flag=true;
		}
		return flag;
	}
}
